package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"gitee.com/yanxingshuyuan/backend/server/models"
	"gitee.com/yanxingshuyuan/backend/server/repositories"
	"github.com/jmoiron/sqlx"
	"github.com/spf13/viper"
)

type Config struct {
	DBString string `json:"dbstring"`
	DataDir  string `json:"datadir"`
}

func initConfig() *Config {
	viper.SetConfigType("toml")
	viper.SetConfigName("author_loader")
	viper.AddConfigPath(".")

	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalf("fatal error: config file %s not found", err)
	}
	config := &Config{}
	config.DBString = viper.GetString("dbstring")
	if config.DBString == "" {
		log.Fatal("Bad Config: No Database String!\n")
		return config
	}
	viper.SetDefault("datadir", "./data/")
	config.DataDir = viper.GetString("datadir")
	return config
}

var authorRepo *repositories.PeopleRepo

func main() {
	config := initConfig()

	db, err := sqlx.Connect("postgres", config.DBString)
	if err != nil {
		log.Fatal("Error connecting database:\n")
	}

	authorRepo = repositories.NewPeopleRepo(db)

	loadAuthors(config.DataDir)
}

func loadAuthors(dir string) {
	pat := filepath.Join(dir, "authors.song*.json")
	files, err := filepath.Glob(pat)
	if err != nil {
		log.Printf("error globing data files: %#v\n", dir)
	}
	if len(files) == 0 {
		log.Printf("No files found for %v\n", pat)
		return
	}
	for n, f := range files {
		fmt.Printf("file:%v,%v\n", n, f)
		loadFile(f)
	}
}

type Author struct {
	Name        string `json:"name"`
	Desc        string `json:"desc"`
	Description string `json:"description"`
	ShortDesc   string `json:"short_description"`
}

func loadFile(file string) {
	f, err := os.Open(file)
	if err != nil {
		log.Printf("Error opening file:%v\n", file)
	}
	defer f.Close()

	var authors []Author
	decoder := json.NewDecoder(f)
	err = decoder.Decode(&authors)
	if err != nil {
		log.Printf("error decoding file: %#v\n", file)
	}

	for _, a := range authors {
		log.Printf("author: %#v\n", a)
		intro := a.Desc
		if intro == "" {
			intro = a.Description
		}
		if intro == "" || intro == "--" {
			intro = a.ShortDesc
		}
		if intro == "" || intro == "--" {
			continue
		}
		// 添加到people表
		p := &models.PersonForm{
			Person: models.Person{
				FullName: a.Name,
				Intro:    intro,
			},
		}
		p.Tags = []models.Tag{}
		// 诗人
		p.Tags = append(p.Tags, models.Tag{
			ID:   10,
			Val:  "诗人",
			Kind: int(models.KindPeople),
			Cat:  int(models.TagCatPeople),
		})
		// 朝代
		/*
			p.Tags = append(p.Tags, models.Tag{
				ID:   63,
				Val:  "唐朝",
				Kind: int(models.KindPeople),
				Cat:  int(models.TagCatEra),
			})
		*/
		p.Tags = append(p.Tags, models.Tag{
			ID:   64,
			Val:  "宋朝",
			Kind: int(models.KindPeople),
			Cat:  int(models.TagCatEra),
		})
		authorRepo.AddPerson(p)

	}
}
